class Solution {
public:

    void reversestring(string& s, int begin, int end) {
        while (begin < end) {
            swap(s[begin++], s[end--]);
        }
    }

    string reverseWords(string s) {
        int last = s.size() - 1;
        int begin = 0;
        int end = 0;
        while (end <= last) {
            while (s[end] != ' ' && end <= last) {
                end++;
            }
            if (begin < end)
                reversestring(s, begin, end - 1);
            begin = end + 1;
            end = begin;
        }
        return s;
    }
};